package com.unience.ec2.eclipse.view;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Collection;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.CoolBar;
import org.eclipse.swt.widgets.CoolItem;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;

import com.unience.aws.monitor.AwsMonitorThread;
import com.unience.aws.monitor.Ec2InstancesListener;
import com.unience.aws.monitor.model.MonitorEc2Instance;
import com.unience.ec2.eclipse.config.Config;
import com.xerox.amazonws.ec2.ReservationDescription.Instance;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class ListEc2InstancesViewPart extends ViewPart implements Ec2InstancesListener{
    public static final String ID_VIEW =
        "com.unience.ec2.eclipse.view.ListEc2InstancesViewPart"; //$NON-NLS-1$
    
    private static Log log = LogFactory.getLog(ListEc2InstancesViewPart.class);

    Composite composite1;
    private Table tableEc2Instances;
    
    protected AwsMonitorThread updater;
    
    ListEc2InstancesViewPart monitor;
    int numInstances = 0;
    private ToolBar toolBar;

    /**
     * 
     */
    public ListEc2InstancesViewPart() {
        super();
        // TODO Auto-generated constructor stub
    }

    /* (non-Javadoc)
     * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
     */
    public void createPartControl(Composite parent) {
    	{
	    	parent.setSize(1200, 1300);
    	}
        composite1 = new Composite(parent, SWT.NULL);
        GridLayout composite1Layout = new GridLayout();
		composite1Layout.makeColumnsEqualWidth = true;
		composite1Layout.horizontalSpacing = 1;
		composite1.setLayout(composite1Layout);

        {
			toolBar = new ToolBar(composite1, SWT.NONE);
			toolBar.setBounds(5, 5, 30, 30);
			{
				ToolItem toolItem1 = new ToolItem(toolBar, SWT.NONE);
				toolItem1.setText("Ssh");
				toolItem1.addSelectionListener(new SelectionAdapter() {
					public void widgetSelected(SelectionEvent event) {			
						//String[] cmd = {"ssh", "-c", "ls > hello"};
						//tableEc2Instances.getSelection()[0].get
						
						MonitorEc2Instance monitorEc2Inst = (MonitorEc2Instance)tableEc2Instances.getSelection()[0].getData();
						String keyDir = monitorEc2Inst.getKeyDir();
						String publicDns = monitorEc2Inst.getInstance().getDnsName();
						String key = monitorEc2Inst.getInstance().getKeyName();
						
						StringBuffer sshBuf = new StringBuffer();
						sshBuf.append("gnome-terminal -x");
						sshBuf.append(" ssh -i ");
						sshBuf.append(keyDir).append('/').append(key).append(' ');
						sshBuf.append("root@").append(publicDns);
						
						
						
						//String sshBuf =  "gnome-terminal -x ssh -i /home/yokinator/applications/Eclipse/accounts/gsg-keypair root@ec2-72-44-53-77.compute-1.amazonaws.com";
						//String[] cmd = {"gnome-terminal", "-x ", sshBuf};
						log.info ( sshBuf.toString());
						try {
							//Process process = Runtime.getRuntime().exec("gnome-terminal");
							Process process = Runtime.getRuntime().exec(sshBuf.toString());
							
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				});
			}
		}
        
        {
        	GridData tableElasticIPLData = new GridData();
			tableElasticIPLData.widthHint = 1200;
			tableElasticIPLData.heightHint = 1289;
			
        	tableEc2Instances = new Table(composite1, SWT.NONE);
        	tableEc2Instances.setLayoutData(tableElasticIPLData);
        	
        	TableColumn tc1 = new TableColumn(tableEc2Instances, SWT.CENTER);
            TableColumn tc2 = new TableColumn(tableEc2Instances, SWT.CENTER);
            TableColumn tc3 = new TableColumn(tableEc2Instances, SWT.CENTER);
            TableColumn tc4 = new TableColumn(tableEc2Instances, SWT.CENTER);
            TableColumn tc5 = new TableColumn(tableEc2Instances, SWT.CENTER);
            TableColumn tc6 = new TableColumn(tableEc2Instances, SWT.CENTER);
            TableColumn tc7 = new TableColumn(tableEc2Instances, SWT.CENTER);
            TableColumn tc8 = new TableColumn(tableEc2Instances, SWT.CENTER);
            TableColumn tc9 = new TableColumn(tableEc2Instances, SWT.CENTER);
            
            
            tc1.setText("InstanceId");
            tc2.setText("AMI");
            tc3.setText("PublicDNS");
            tc4.setText("PrivateDNS");
            tc5.setText("State");
            tc6.setText("KeyName");
            tc7.setText("Groups");
            tc8.setText("LaunchTime");
            tc9.setText("Zone");
            
            
            tc1.setWidth(120);
            tc2.setWidth(120);
            tc3.setWidth(180);
            tc4.setWidth(180);
            tc5.setWidth(100);
            tc6.setWidth(100);
            tc7.setWidth(100);
            tc8.setWidth(100);
            tc9.setWidth(100);
            
            tableEc2Instances.setHeaderVisible(true);
        }
        

        updater = Config.getInstance().getUpdater();
       	
        updater.addListener(this);
        
        
    }

    /* (non-Javadoc)
     * @see org.eclipse.ui.IWorkbenchPart#setFocus()
     */
    public void setFocus() {
        // TODO Auto-generated method stub
    }
    
    /**
     * Cleans up all resources created by this ViewPart.
     */
    public void dispose() {
        super.dispose();
    }
    
    private void setInstances(final Collection<MonitorEc2Instance> instancesList){
    	DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
    	tableEc2Instances.removeAll();
    	for (MonitorEc2Instance monitorEc2Instance : instancesList) {
    		TableItem item1 = new TableItem(tableEc2Instances, SWT.NONE);
    		Instance ec2 = monitorEc2Instance.getInstance();
    		List<String> groups = monitorEc2Instance.getGroups();
    		StringBuffer gr = new StringBuffer();
    		for (String string : groups) {
				gr.append(string).append(',');
				
			}
    		
    		

    		String formatedDate = df.format(ec2.getLaunchTime().getTime());
    		item1.setData(monitorEc2Instance);
            item1.setText(new String[] { ec2.getInstanceId(),ec2.getImageId(), ec2.getDnsName(), ec2.getPrivateDnsName(), ec2.getState(), ec2.getKeyName(), gr.toString(),formatedDate, ec2.getAvailabilityZone()});
            ImageDescriptor descriptor = null;
            if ( ec2.getStateCode() == 16){
				descriptor =ImageDescriptor.createFromFile(Config.class,"started.png" );
			}else if (ec2.getStateCode() == 48){
				descriptor =ImageDescriptor.createFromFile(Config.class,"terminated.png" );
			}else {
				descriptor =ImageDescriptor.createFromFile(Config.class,"pending.png" );
			}
            
            item1.setImage(descriptor.createImage());
            
		}
    	
        
        
        
    	
    }
    
    public void update(final Collection<MonitorEc2Instance> instancesList, final Object listener) {
		
        
    	monitor = this;
    

		if (instancesList != null){
			numInstances =  instancesList.size();
		}
		else{
			numInstances = 0;
		}
		
		 Config.getInstance().getDisplay().asyncExec(new Runnable() {
			  public void run(){
			    	
			    	final IWorkbench workbench = PlatformUI.getWorkbench();
					if (workbench == null)
						return;
					final Display display = workbench.getDisplay();
					
					if (!display.isDisposed()){
				    	log.info("updating chart numInstances " + numInstances);
				    	monitor.setInstances(instancesList);
					}
			      }
			    });
			  
		
	}
    
}
